package com.studio5704website.infrastructure.service;

import com.studio5704website.core.user.EncryptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import javax.crypto.Cipher;


/**
 * @author 高威
 * 加密解密服务实现类
 */
@Component
public class DefaultEncryptService implements EncryptService {
    private Cipher encryptCipher;

    private Cipher decrpytCipher;

    @Autowired
    public DefaultEncryptService(@Qualifier("encryptCipher") Cipher encryptCipher, @Qualifier("decryptCipher") Cipher decrpytCipher) {
        this.encryptCipher = encryptCipher;
        this.decrpytCipher = decrpytCipher;
    }

    @Override
    public String encrypt(String password) {
        try {
            byte[] bytes = encryptCipher.doFinal(password.getBytes());
            return Base64Utils.encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return password;
        }

    }

    @Override
    public boolean check(String checkPassword, String realPassword) {
        try {
            byte[] bytes = decrpytCipher.doFinal(Base64Utils.decodeFromString(checkPassword));
            return realPassword.equals(new String(bytes));
        } catch (Exception e) {
            e.printStackTrace();
            return checkPassword.equals(realPassword);
        }
    }


}

